<template>
  <div style="background: #f5f7fa; padding: 24px;">
    <a-row :gutter="[16, 16]" style="margin-bottom: 24px;">
      <a-col :span="8">
        <a-card>
          <a-statistic title="总分" :value="totalScore" suffix="分" />
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card>
          <a-statistic 
            title="加分" 
            :value="addScore" 
            suffix="分" 
            :value-style="{ color: '#52c41a' }" 
          />
        </a-card>
      </a-col>
      <a-col :span="8">
        <a-card>
          <a-statistic 
            title="减分" 
            :value="minusScore" 
            suffix="分" 
            :value-style="{ color: '#f5222d' }" 
          />
        </a-card>
      </a-col>
    </a-row>
    <div style="background: #fff; padding: 24px; border-radius: 8px; margin-bottom: 24px;">
      <h3 style="margin-bottom: 16px;">分数趋势分析</h3>
      <div ref="scoreChartRef" style="width: 100%; height: 400px;"></div>
    </div>
    <div style="background: #fff; padding: 24px; border-radius: 8px; margin-bottom: 24px;">
      <h3 style="margin-bottom: 16px;">部门请假情况</h3>
      <div ref="leaveChartRef" style="width: 100%; height: 400px;"></div>
    </div>
    <!-- 请假类型和分数类型玫瑰图 -->
    <a-row :gutter="[16, 16]" style="margin-bottom: 24px;">
      <a-col :span="12">
        <div style="background: #fff; padding: 24px; border-radius: 8px;">
          <h3 style="margin-bottom: 16px;">请假类型分布</h3>
          <div ref="leaveTypeChartRef" style="width: 100%; height: 400px;"></div>
        </div>
      </a-col>
      <a-col :span="12">
        <div style="background: #fff; padding: 24px; border-radius: 8px;">
          <h3 style="margin-bottom: 16px;">分数类型分布</h3>
          <div ref="scoreTypeChartRef" style="width: 100%; height: 400px;"></div>
        </div>
      </a-col>
    </a-row>
    <!-- 表格部分 -->
    <div style="background: #fff; padding: 24px; border-radius: 8px;">
      <a-table :columns="columns" :data-source="dataSource" row-key="id">
        <template #bodyCell="{ column, record }">

          <template v-if="column.key === 'createTime'">
            {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
          </template>
          <template v-else-if="column.dataIndex === 'operator'">
            {{ record.operator?.userName || '-' }}
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import 'echarts-wordcloud'
import { Card, Row, Col, Statistic, Table, Button, Space, message } from 'ant-design-vue'
import { getScoreByPageUsingPost } from '@/api/scoreController'
import { getLeavePageUsingPost } from '@/api/leaveController'
import dayjs from 'dayjs'
// 统计卡片数据
const totalScore = ref(0)
const addScore = ref(0)
const minusScore = ref(0)

// 折线图数据
const chartData = ref<{ date: string, score: number }[]>([])

// 表格数据
const columns = [
  { title: '用户ID', dataIndex: 'userId', key: 'userId' },
  { title: '用户名', dataIndex: 'userName', key: 'userName' },
  { title: '类型', dataIndex: 'type', key: 'type' },
  { title: '原因', dataIndex: 'reason', key: 'reason' },
  { title: '分数', dataIndex: 'score', key: 'score' },
  { title: '操作员', dataIndex: 'operator', key: 'operator' },
  { title: '创建时间', dataIndex: 'createTime', key: 'createTime' },
]
const dataSource = ref<API.ScoreManageVo[]>([])

// 图表引用
const scoreChartRef = ref<HTMLDivElement | null>(null)
const leaveChartRef = ref<HTMLDivElement | null>(null)
const leaveTypeChartRef = ref<HTMLDivElement | null>(null)
const scoreTypeChartRef = ref<HTMLDivElement | null>(null)
let scoreChartInstance: echarts.ECharts | null = null
let leaveChartInstance: echarts.ECharts | null = null
let leaveTypeChartInstance: echarts.ECharts | null = null
let scoreTypeChartInstance: echarts.ECharts | null = null

// 数据请求与统计
const fetchData = async () => {
  try {
    // 获取分数数据
    const scoreRes = await getScoreByPageUsingPost({
      current: 1,
      pageSize: 1000,
      sortField: 'createTime',
      sortOrder: 'ascend'
    })

    if (!scoreRes.data?.data?.records) {
      message.error('获取分数数据失败')
      return
    }

    const scoreRecords = scoreRes.data.data.records

    // 统计卡片数据
    let total = 0, add = 0, minus = 0
    scoreRecords.forEach(item => {
      if (item.score) {
        total += item.score
        if (item.type === '加分') add += item.score
        if (item.type === '减分') minus += item.score
      }
    })
    totalScore.value = total
    addScore.value = add
    minusScore.value = minus

    // 处理折线图数据
    const dateMap: Record<string, { add: number, minus: number }> = {}
    scoreRecords.forEach(item => {
      const date = item.createTime ? item.createTime.slice(0, 10) : '未知'
      if (!dateMap[date]) {
        dateMap[date] = { add: 0, minus: 0 }
      }
      if (item.type === '加分') {
        dateMap[date].add += item.score || 0
      } else if (item.type === '减分') {
        dateMap[date].minus += item.score || 0
      }
    })

    // 转换数据格式并排序
    const dates = Object.keys(dateMap).sort()
    const addScores = dates.map(date => dateMap[date].add)
    const minusScores = dates.map(date => dateMap[date].minus)

    // 初始化折线图
    if (scoreChartRef.value) {
      if (!scoreChartInstance) {
        scoreChartInstance = echarts.init(scoreChartRef.value)
      }

      scoreChartInstance.setOption({
        title: {
          text: '整体分数趋势',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          formatter: function(params: any) {
            let result = params[0].axisValue + '<br/>'
            params.forEach((param: any) => {
              const value = param.value
              const sign = param.seriesName === '加分' ? '+' : '-'
              result += `${param.marker} ${param.seriesName}: ${sign}${Math.abs(value)}<br/>`
            })
            return result
          }
        },
        legend: {
          data: ['加分', '减分'],
          top: 30
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: dates,
          axisLabel: {
            rotate: 45
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: function(value: number) {
              return value > 0 ? '+' + value : value
            }
          }
        },
        series: [
          {
            name: '加分',
            data: addScores,
            type: 'line',
            smooth: true,
            areaStyle: {
              opacity: 0.1
            },
            lineStyle: {
              color: '#52c41a',
              width: 2
            },
            itemStyle: {
              color: '#52c41a'
            }
          },
          {
            name: '减分',
            data: minusScores,
            type: 'line',
            smooth: true,
            areaStyle: {
              opacity: 0.1
            },
            lineStyle: {
              color: '#f5222d',
              width: 2
            },
            itemStyle: {
              color: '#f5222d'
            }
          }
        ]
      })
    }

    // 获取请假数据
    const leaveRes = await getLeavePageUsingPost({
      current: 1,
      pageSize: 1000,
      sortField: 'createTime',
      sortOrder: 'descend'
    })

    if (!leaveRes.data?.data?.records) {
      message.error('获取请假数据失败')
      return
    }

    const leaveRecords = leaveRes.data.data.records


    // 处理部门请假数据
    const departmentMap: Record<string, number> = {}
    leaveRecords.forEach((record: any) => {
      const section = record?.section || '未分配部门'
      departmentMap[section] = (departmentMap[section] || 0) + 1
    })

    // 处理请假类型数据
    const leaveTypeMap: Record<string, number> = {}
    leaveRecords.forEach((record: any) => {
      const category = record?.category || '其他'
      leaveTypeMap[category] = (leaveTypeMap[category] || 0) + 1
    })

    // 处理分数原因数据
    const reasonMap: Record<string, { value: number, type: string }> = {}
    scoreRecords.forEach((record: any) => {
      if (record.reason) {
        if (!reasonMap[record.reason]) {
          reasonMap[record.reason] = { value: 0, type: record.type }
        }
        reasonMap[record.reason].value += 1
      }
    })

    // 转换为数组并排序
    const reasonData = Object.entries(reasonMap)
      .map(([name, data]) => ({
        name,
        value: data.value,
        type: data.type
      }))
      .sort((a, b) => b.value - a.value)
      .slice(0, 50) // 只取前50个原因

    console.log('词云图数据:', reasonData) // 添加调试日志

    // 转换为数组并排序
    const departmentData = Object.entries(departmentMap)
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)

    const leaveTypeData = Object.entries(leaveTypeMap)
      .map(([name, value]) => ({ name, value }))
      .sort((a, b) => b.value - a.value)

    // 初始化部门请假柱状图
    if (leaveChartRef.value) {
      if (!leaveChartInstance) {
        leaveChartInstance = echarts.init(leaveChartRef.value)
      }

      leaveChartInstance.setOption({
        title: {
          text: '各部门请假情况',
          left: 'center'
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          },
          formatter: function(params: any) {
            const param = params[0]
            return `${param.name}<br/>请假次数：${param.value}次`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: departmentData.map(item => item.name),
          axisLabel: {
            interval: 0,
            rotate: 30
          }
        },
        yAxis: {
          type: 'value',
          name: '请假次数'
        },
        series: [
          {
            name: '请假次数',
            type: 'bar',
            data: departmentData.map(item => item.value),
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            }
          }
        ]
      })
    }

    // 初始化请假类型玫瑰图
    if (leaveTypeChartRef.value) {
      if (!leaveTypeChartInstance) {
        leaveTypeChartInstance = echarts.init(leaveTypeChartRef.value)
      }

      leaveTypeChartInstance.setOption({
        title: {
          text: '请假类型分布',
          left: 'center'
        },
        tooltip: {
          trigger: 'item',
          formatter: function(params: any) {
            return `${params.name}<br/>请假次数：${params.value}次<br/>占比：${params.percent}%`
          }
        },
        legend: {
          orient: 'vertical',
          left: 'left',
          data: leaveTypeData.map(item => item.name)
        },
        series: [
          {
            name: '请假类型',
            type: 'pie',
            radius: ['40%', '70%'],
            avoidLabelOverlap: false,
            itemStyle: {
              borderRadius: 10,
              borderColor: '#fff',
              borderWidth: 2
            },
            label: {
              show: false,
              position: 'center'
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: leaveTypeData.map(item => ({
              value: item.value,
              name: item.name
            }))
          }
        ]
      })
    }

    // 初始化分数原因词云图
    if (scoreTypeChartRef.value) {
      if (!scoreTypeChartInstance) {
        scoreTypeChartInstance = echarts.init(scoreTypeChartRef.value)
      }

      const option = {
        title: {
          text: '分数原因分布',
          left: 'center'
        },
        tooltip: {
          show: true,
          formatter: function(params: any) {
            return `${params.name}<br/>类型：${params.data.type}<br/>出现次数：${params.value}次`
          }
        },
        series: [{
          type: 'wordCloud',
          shape: 'circle',
          left: 'center',
          top: 'center',
          width: '90%',
          height: '90%',
          right: null,
          bottom: null,
          sizeRange: [12, 60],
          rotationRange: [-45, 45],
          rotationStep: 5,
          gridSize: 6,
          drawOutOfBound: false,
          layoutAnimation: true,
          textStyle: {
            fontFamily: 'sans-serif',
            fontWeight: 'bold',
            color: function (params: any) {
              return params.data.type === '加分' ? '#52c41a' : '#f5222d'
            }
          },
          emphasis: {
            focus: 'self',
            textStyle: {
              shadowBlur: 10,
              shadowColor: '#333'
            }
          },
          data: reasonData
        }]
      }

      console.log('词云图配置:', option) // 添加调试日志
      scoreTypeChartInstance.setOption(option)

      // 添加窗口大小变化时的自适应
      window.addEventListener('resize', () => {
        scoreTypeChartInstance?.resize()
      })
    }

    dataSource.value = scoreRecords
  } catch (error) {
    message.error('获取数据失败')
    console.error(error)
  }
}

onMounted(fetchData)
</script>

<style scoped>
/* 可根据需要自定义样式 */
.ant-card {
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);
}
</style>
